package com.luocj.muke.demo.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luocj.muke.demo.R;
import com.luocj.muke.demo.adapter.NewsAdapter;
import com.luocj.muke.demo.model.NewsModel;
import com.luocj.muke.demo.utils.Url;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class NewsFragment extends BaseFragment {

    private static final String TAG = NewsFragment.class.getSimpleName();
    private View news;
    private TextView tvFinishLoadMore;
    private RecyclerView recyclerview;
    private SwipeRefreshLayout srl;
    private NewsAdapter adapter;
    private int lastVisibleItem = 0;
    private int page = 10;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        news = inflater.inflate(R.layout.fragment_news, container, false);
        return news;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        recyclerview = news.findViewById(R.id.rv_news);
        srl = news.findViewById(R.id.srl);
        tvFinishLoadMore = news.findViewById(R.id.tv_finish_loadmore);
        srl.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);

        srl.setRefreshing(true);
        loadData();
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 10;
                        //刷新完成
                        loadData();
                        srl.setRefreshing(false);
                        Toast.makeText(getActivity(), "更新了", Toast.LENGTH_SHORT).show();

                    }

                }, 2000);
            }
        });

        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {

                    page += 10;
                    loadMore(page);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                        }
                    }, 3000);


                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerview.setLayoutManager(linearLayoutManager);
        adapter = new NewsAdapter(getActivity(), getNews());
        recyclerview.setAdapter(adapter);
    }

    private void loadMore(int page) {
        OkGo.<String>get(Url.TIAN_XING + page)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ArrayList<NewsModel.NewslistBean> temp = new ArrayList<>();
                        NewsModel newsModel = JSONObject.parseObject(response.body(), NewsModel.class);
                        for (int i = newsModel.getNewslist().size() - 1; i >= newsModel.getNewslist().size() - 10; i--) {
                            temp.add(newsModel.getNewslist().get(i));
                        }

                        Collections.reverse(temp);
                        adapter.setLoadMore(temp);

                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {

                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }

    private ArrayList<NewsModel.NewslistBean> getNews() {
        return new ArrayList<NewsModel.NewslistBean>();
    }

    private ArrayList<String> getNewData() {
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            strings.add("item new  :" + i);
        }
        return strings;
    }

    private ArrayList<String> getData() {
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            strings.add("item :" + i);
        }
        return strings;
    }

    @Override
    protected void loadData() {
        OkGo.<String>get(Url.TIAN_XING + page)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        NewsModel newsModel = JSONObject.parseObject(response.body(), NewsModel.class);
                        Log.i(TAG, "onSuccess: " + newsModel.getCode());
                        List<NewsModel.NewslistBean> newslist = newsModel.getNewslist();
                        srl.setRefreshing(false);
                        if (adapter != null) {
                            adapter.setNewdata(newslist);
                        }
                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {

                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i(TAG, "onError: " + response.body());
                    }
                });


    }
}
